package com.atguigu.juc.day02.rw;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Demo02WriteRepelRead {

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private Lock readLock = readWriteLock.readLock();
    private Lock writeLock = readWriteLock.writeLock();

    public void doWriteOperation() {
        try {
            writeLock.lock();

            System.out.println(Thread.currentThread().getName() + " 写操作【开始】。");

            TimeUnit.SECONDS.sleep(3);

            System.out.println(Thread.currentThread().getName() + " 写操作【结束】。");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {

            writeLock.unlock();

        }
    }

    public void doReadOperation() {

        try {
            // 加读锁
            readLock.lock();

            System.out.println(Thread.currentThread().getName() + " 线程开始执行读操作。");

            TimeUnit.SECONDS.sleep(5);

            System.out.println(Thread.currentThread().getName() + " 线程结束执行读操作。");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 解读锁
            readLock.unlock();
        }

    }

    public static void main(String[] args) {

        Demo02WriteRepelRead demo = new Demo02WriteRepelRead();

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                demo.doReadOperation();
            }, "thread-r-" + i).start();
        }

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                demo.doWriteOperation();
            }, "thread-w-" + i).start();
        }

    }

}
